require 'Object'
require 'Utility'
require 'Config'

MENU_ITEM_ALIGN_LEFT = SCREEN_WIDTH / 3
MENU_ITEM_SPACING = 50

class Menu < DrawableObject
  attr_accessor :items
  
  def initialize
		#super(nil)
    @items = []
    $game.objects << self
		@active = false
  end
  
  def add(item)
    item.position = @items.length + 1
    if @items.empty? then
      item.is_active = true
    end
		item.active = @active
    @items << item
  end
	
  def select_next
    i = selected_index
    selected_item.deactivate

    i = i + 1
    i = i % (@items.length)
    @items[i].activate
  end
  
  def select_prev
    i = selected_index
    selected_item.deactivate
    
    i = i - 1
    if (i < 0) then
      i = @items.length - 1
    end
    @items[i].activate
  end
  
  def selected_item
    @items.each do |item|
      if item.is_active then
        return item
      end
    end
    
    return nil
  end
  
  def active=(value)
    @active = value
    @items.each do 
      |item| item.active = value
    end
  end
  
  def selected_index
    return @items.index(selected_item)
  end
  
  def select
    selected_item.select
  end
  
  def draw
    # do nothing
  end
  
end

class MenuItem < DrawableObject
  attr_accessor :label, :position, :value, :is_active
  
  
  def initialize(label, &action)
    @label,  @action = label, action
    
    @font = Gosu::Font.new($game, Gosu::default_font_name, 20)
    
    @active_colour = 0xffffffff
    @inactive_colour = 0xff2cc5ff
    
    @is_active = false
    
    #@img = Gosu::Image.from_text($game, label, Gosu::default_font_name, 20, 
    #  0, SCREEN_WIDTH, :center)
      
    $game.objects << self
    super
    
  end
  
  def activate
    #puts label + ' activated'
    @is_active = true
  end
  
  def deactivate
    @is_active = false
  end
  
  def select
    @action.call
  end
  
  def draw
    colour = @is_active ? @active_colour : @inactive_colour
    #@img.draw_rot(SCREEN_WIDTH/2, @position * MENU_ITEM_SPACING, ZOrder::GUI, 0)
    @font.draw_rel(label, SCREEN_WIDTH/2, position * MENU_ITEM_SPACING,  ZOrder::GUI, 
      0.5,0.5, 1,1, colour)
  end
  
end